//
//  FlowLayout.m
//  WaterFall1109
//
//  Created by Mr、J on 15/11/9.
//  Copyright © 2015年 chenjun. All rights reserved.
//

#import "FlowLayout.h"
#define HEIGHT  [[UIScreen mainScreen]bounds].size.height / 667
#define WIDTH   [[UIScreen mainScreen]bounds].size.width / 375
@interface FlowLayout ()


@end

@implementation FlowLayout
- (void)dealloc{
    [_array release];
    [super dealloc];
}
//重写系统的prepareLayout方法，准备布局item之前会被调用
-(void)prepareLayout
{
    //调用父类的方法
    [super prepareLayout];
    
    self.maxHeight = 0;
    
    //用来存放item属性
    self.array = [NSMutableArray array];
    
    //第一列item y坐标的初始值
    CGFloat leftY = 0;
    
    //第二列item y坐标的初始值
    CGFloat rightY = 0;
    
    
    //计算contentView
    //第一步
    CGFloat maxLeft = 0;
    CGFloat maxRight = 0;
    
    //计算当前分区有多少个item
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    //设置每个item的属性
    for (int i = 0; i < count; i++) {
        
        //生成item的下标
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        
        //根据item下标取出每个item属性对象，通过它能设置item的frame
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        
        //默认X坐标为0
        float offSetX = 0;
        
        if (i % 2 == 0) {
            //设置第一列item X坐标
            offSetX = 5 * WIDTH;
        }else {
            offSetX = 190 * WIDTH;
        }
        
        //获取协议返回的size
        CGSize itemSize = [self.delegate collectionview:self.collectionView layout:self sizeForItemAtItemIndexPath:index];
     //设置每一个item的属性
        if (i % 2 == 0) {
            //设置第一列item
            attributes.frame = CGRectMake(offSetX, leftY, itemSize.width, itemSize.height);
            //记录左侧所有item高度
            maxLeft = leftY + itemSize.height;
            leftY += itemSize.height + 5 * HEIGHT;
            
        }else {
            attributes.frame = CGRectMake(offSetX, rightY, itemSize.width, itemSize.height);
            maxRight = rightY + itemSize.height;
            rightY += itemSize.height + 5 * WIDTH;
        }
        
        self.maxHeight = maxLeft > maxRight ? maxLeft + 5 * HEIGHT : maxRight + 5 * HEIGHT;
        
        //存入数组中
        [self.array addObject:attributes];
        
    }
    
    
}

//重写系统方法，初始的layout的外观由该方法返回的UICollectionViewLayoutAttributes来决定
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < [self.array count]; i++) {
        UICollectionViewLayoutAttributes *att = [self.array objectAtIndex:i];
        //判断第二个rect是不是在第一个rect范围之内
        if (CGRectIntersectsRect(rect, att.frame)) {
            
            [arr addObject:att];
        }
        
    }
    return arr;
}

//重新设置滑动范围contentSize
-(CGSize)collectionViewContentSize
{
    return CGSizeMake(self.collectionView.frame.size.width, self.maxHeight);
}

@end
